/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.base.service.cars;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.common.validator.ValidatorUtils;
import com.jeesite.modules.base.dao.cars.TcarConfigurationDao;
import com.jeesite.modules.base.dao.cars.TcarDao;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.cars.TcarConfiguration;
import com.jeesite.modules.custom.service.CodeRuleService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 车辆档案Service
 *
 * @author shengbin
 * @version 2021-03-01
 */
@Service
@Transactional(readOnly = true)
public class TcarService extends CrudService < TcarDao, Tcar > {

    @Autowired
    private TcarConfigurationDao tcarConfigurationDao;
    @Autowired
    private CodeRuleService codeRuleService;

    /**
     * 获取单条数据
     *
     * @param tcar
     * @return
     */
    @Override
    public Tcar get(Tcar tcar) {
        Tcar entity = super.get(tcar);
        if (entity != null) {
            TcarConfiguration tcarConfiguration = new TcarConfiguration(entity);
            tcarConfiguration.setStatus(TcarConfiguration.STATUS_NORMAL);
            entity.setTcarConfigurationList(tcarConfigurationDao.findList(tcarConfiguration));
        }
        return entity;
    }

    /**
     * 查询分页数据
     *
     * @param tcar        查询条件
     * @param //tcar.page 分页对象
     * @return
     */
    @Override
    public Page < Tcar > findPage(Tcar tcar) {
        return super.findPage(tcar);
    }

    /**
     * 保存数据（插入或更新）
     *
     * @param tcar
     */
    @Override
    @Transactional(readOnly = false)
    public void save(Tcar tcar) {
        if (tcar.getIsNewRecord()) {
            tcar.setCarId(codeRuleService.getCode("car"));
            tcar.setCreateBy(UserUtils.getUser().getUserCode());
            tcar.setUpdateBy(UserUtils.getUser().getUserCode());
        } else {
            tcar.setUpdateBy(UserUtils.getUser().getUserCode());
        }
        String model = tcar.getModel();
        String year = tcar.getYear();
        String brand = tcar.getBrand();
        String pinpai = DictUtils.getDictLabel("car_pinpai", brand, "");
        String niankuan = DictUtils.getDictLabel("car_niankuan", year, "");
        tcar.setCarName(pinpai + " " + model + " " + niankuan);

        super.save(tcar);
        if (tcar.getIsNewRecord()) {
            codeRuleService.updateCurrentNumber("car");
        }
        // 保存 Tcar子表
        for (TcarConfiguration tcarConfiguration : tcar.getTcarConfigurationList()) {
            if (!TcarConfiguration.STATUS_DELETE.equals(tcarConfiguration.getStatus())) {
                tcarConfiguration.setCarId(tcar);
                if (tcarConfiguration.getIsNewRecord()) {
                    tcarConfigurationDao.insert(tcarConfiguration);
                } else {
                    tcarConfigurationDao.update(tcarConfiguration);
                }
            } else {
                tcarConfigurationDao.delete(tcarConfiguration);
            }
        }

    }

    /**
     * 更新状态
     *
     * @param tcar
     */
    @Override
    @Transactional(readOnly = false)
    public void updateStatus(Tcar tcar) {
        super.updateStatus(tcar);
    }

    /**
     * 删除数据
     *
     * @param tcar
     */
    @Override
    @Transactional(readOnly = false)
    public void delete(Tcar tcar) {
        super.delete(tcar);
        TcarConfiguration tcarConfiguration = new TcarConfiguration();
        tcarConfiguration.setCarId(tcar);
        tcarConfigurationDao.deleteByEntity(tcarConfiguration);
    }

    /**
     * 导入车辆配置数据
     *
     * @param file 导入车辆配置数据文件
     */
    @Transactional(readOnly = false)
    public String importData(MultipartFile file) {
        if (file == null) {
            throw new ServiceException(text("请选择导入的数据文件！"));
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        try (ExcelImport ei = new ExcelImport(file, 2, 0)) {
            List < TcarConfiguration > list = ei.getDataList(TcarConfiguration.class);
            for (TcarConfiguration tcarConfiguration : list) {
                try {
                    // 验证数据文件
                    ValidatorUtils.validateWithException(tcarConfiguration);
                    // 车辆编号验证
                    if (StringUtils.isBlank(tcarConfiguration.getCarId().getCarId())) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、车辆编号 " + tcarConfiguration.getCarId()
                                + " 导入失败：车辆编号不能为空");
                        continue;
                    }
                    tcarConfigurationDao.insert(tcarConfiguration);

                } catch (Exception e) {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、车辆编号 " + tcarConfiguration.getCarId() + " 导入失败：";
                    if (e instanceof ConstraintViolationException) {
                        ConstraintViolationException cve = (ConstraintViolationException) e;
                        for (ConstraintViolation < ? > violation : cve.getConstraintViolations()) {
                            msg += Global.getText(violation.getMessage()) + " (" + violation.getPropertyPath() + ")";
                        }
                    } else {
                        msg += e.getMessage();
                    }
                    failureMsg.append(msg);
                    logger.error(msg, e);
                }
            }
        } catch (Exception e) {
            failureMsg.append(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}